<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Chat</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"/>

    <!-- Awesome Font-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <script src='https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js'></script>
    <style>
        .chats-row div {
            height: 50%;
            border: 1px solid #ddd;
            padding: 0px;
        }

        .media-object {
            max-width: 64px;
        }

        .current-chat {
            height: 100vh;
            border: 1px solid #ddd;
        }

        .current-chat-area {
            padding-top: 10px;
            overflow: auto;
            height: 92vh;
        }

        .chat-input {
            margin-top: 10px;
            margin-bottom: 10px;
            height: 8vh;
        }

        .chat-input textarea {
            width: 100%;
            border: none;
        }
        .chat-input button {
            position: absolute;
            right: 10px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12 current-chat">
            <div class="row current-chat-area">
                <div class="col-md-12">
                    <ul class="media-list">
                        <li th:each="message : ${messages}" class="media">
                            <div class="media-body">
                                <div class="media">
                                    <a class="pull-left" href="#">
                                        <img class="media-object img-circle "
                                             th:src="${message.getUser().getAvatarImageLink()}"/>
                                    </a>
                                    <div class="media-body" th:inline="none">
                                        <span th:utext="${message.getContent()}" th:remove="tag">title</span>
                                        <br/>
                                        <small class="text-muted"
                                               th:text="${message.getUser().getName()
                                               + ' | '
                                               + #temporals.format(message.getSent(), 'dd-MM-yyyy, HH:mm:ss')}"></small>
                                        <hr/>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="row chat-input">
                <div class="col-sm-12">
                    <textarea class="write_msg" placeholder="Type a message"></textarea>
                    <button class="msg_send_btn" type="button"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:inline="javascript">
    /*<![CDATA[*/
    var messageTemplate = _.template(
        '<li class="media">'
        + '<div class="media-body">'
        + '' + '<div class="media">'
        + '' + '' + '<a class="pull-left" href="#">'
        + '' + '' + '' + '<img class="media-object img-circle" src="<%= user.avatarImageLink %>"/>'
        + '' + '' + '</a>'
        + '' + '' + '<div class="media-body">'
        + '' + '' + '' + '<%= content %>'
        + '' + '' + '' + '<br/>'
        + '' + '' + '' + '<small class="text-muted"><%= user.name  %> | <%= moment(sent).format("DD-MM-YYYY, HH:mm:ss") %></small>'
        + '' + '' + '' + '<hr/>'
        + '' + '' + '</div>'
        + '' + '</div>'
        + '</div>' +
        '</li>',
    { 'imports': { 'moment': moment } });

    var user = { };
    $.ajax({
        url: 'https://randomuser.me/api/',
        dataType: 'json',
        success: function(data) {
            user.name = data.results[0].name.first + " " + data.results[0].name.last;
            user.avatarImageLink = data.results[0].picture.large;
        }
    });
    var lastMessageId = /*[[${lastMessageId}]]*/'';
    var mediaList = $('.media-list');
    var chatArea = $('.current-chat-area');
    var messageButton = $('.chat-input button');
    var messageInput = $('.chat-input textarea');

    messageButton.on("click", function() {
        var content = messageInput.val();
        messageInput.val("");
        if (content) {
            $.post({
                url: "/api/v1/messages",
                data: JSON.stringify({content: content , user: user, sent: new Date().toISOString()}),
                contentType: 'application/json'
            });
        }
    })

    chatArea.animate({scrollTop: mediaList.height()}, 1);
    setInterval(function () {
        $.get("/api/v1/messages", {lastMessageId: lastMessageId}).done(function (data, status, request) {
            if (data) {
                data.forEach(function (v) {
                    mediaList.append(messageTemplate(v));
                });

                chatArea.stop();
                chatArea.animate({scrollTop: mediaList.height()}, 500);
            }

            lastMessageId = request.getResponseHeader('lastMessageId');
        });
    }, 1000);

    /*]]>*/
</script>
</body>
</html>